﻿﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace NFinal
{
#if (!AspNET && !MicrosoftOwin)
    using AppFunc = Func<IDictionary<string, object>, Task>;
    public struct NFinalOwinMiddleware
    {
        private readonly AppFunc _next;
        private static string rootDir = null;
        public NFinalOwinMiddleware(AppFunc next)
        {
            this._next = next;
        }
        public async Task Invoke(IDictionary<string, object> environment)
        {
            string requestPath = (string)environment["owin.RequestPathBase"] + (string)environment["owin.RequestPath"];
            int actionId= ActionSearch.Search(requestPath);
            if (rootDir == null)
            {
                rootDir = NFinal.Utility.rootPath;
            }
            if (actionId > 0)
            {
                try
                {
                    @{@Model.project}.NFinalOwinRouter.Run(environment, actionId);
                }
                catch (Exception e)
                {
                    NFinal.Owin.Request request = environment.GetRequest();
                    NFinal.NFinalOwinBaseAction writer = new NFinalOwinBaseAction(environment, request,CompressMode.Deflate);
                    writer.SetResponseHeader("Content-Type", "text/html; charset=utf-8");
                    writer.SetResponseStatusCode(200);
                    writer.Write("错误消息：<br/>");
                    writer.Write(e.Message);
                    writer.Write("<br/>");
                    writer.Write("请求时发生错误：<br>");
                    writer.Write(requestPath);
                    writer.Write("<br/>");
                    writer.Write("错误跟踪：</br>");
                    string[] stackTraces = e.StackTrace.Split('\n');
                    for (int i = 0; i < stackTraces.Length; i++)
                    {
                        writer.Write(stackTraces[i]);
                        writer.Write("</br>");
                    }
                    writer.Close();
                }
                //return Task.FromResult(0);.net 4.5;
                await FromResult<int>(0);
            }
            else
            {
                await _next.Invoke(environment);
            }
        }
        public static Task<TResult> FromResult<TResult>(TResult resultValue)
        {
            var completionSource = new TaskCompletionSource<TResult>();
            completionSource.SetResult(resultValue);
            return completionSource.Task;
        }
    }
#endif
}